import {
  loadMicroApp
} from 'qiankun';
import router from '@/router/index.js';
import actions from './actions.js';
import {
  microAppConfig
} from './config.js'

import pinia from '@/store/index';
import useTagsViewStore from '@/store/modules/tagsView'
import usePermissionStore from '@/store/modules/permission'
import useAppStore from "@/store/modules/app";
import {tabMap} from '@/data/router.js'
const viewStore = useTagsViewStore(pinia)
const permissionStore = usePermissionStore(pinia)
const appStore = useAppStore(pinia)
let time = null

const sidebarRouters = computed(() => permissionStore.sidebarRouters);

//  判断当前页签是否是微应用下的页面
const isMicroApp = function (path) {
  return microAppConfig.some(item => path.startsWith(item.activeRule))
}

// 查找当前匹配微应用
const findMicroAppByPath = function (path) {
  return microAppConfig.find(item => path.startsWith(item.activeRule))
}

class Tabs {
  // 切换父级页面
  createIframePage(path, fullPath, query, params, meta, name) {
    // 获取微应用配置
    let installAppMap = { ...viewStore.installAppMap }
    return new Promise(async(resolve) => {
      for (let appName in installAppMap) {
        // 等待 parcel 挂载完成，然后再调用 update
        // await installAppMap[appName].mountPromise.then(()=>{
        //   if (installAppMap[appName].getStatus() === 'MOUNTED') {
        //     installAppMap[appName].update({
        //       routerEvent: {
        //         type: 'visible' // 如果不是当前活跃的就隐藏
        //       }
        //     })
        //   }
        // })
      }
      //  先判断跳转页面是否存在tabList 或者 存在它的父页面
      const find = viewStore.cachedViews.find((item) => item.path?.startsWith(path))
      // 临时方案  主页 no-name 问题
      const tabInfo = tabMap[path];
      if(tabInfo){
        viewStore.activeTab = {
          appName: tabInfo.appName,
          fullPath: path,
          name: tabInfo.name,
          path,
        }
        resolve(true)
      }
      // 如果不存在活跃tab列表
      if (find) {
        viewStore.activeTab = find
      } else {
        viewStore.addCachedView({
          appName: 'main', // 主应用
          path,
          fullPath,
          query,
          params,
          title: meta.title,
          name
        })
      }
      resolve(true)
    })
  }

  // 切换微应用页面
  createMicoPage(path, fullPath, query, params, meta, name) {
    return new Promise((resolve, reject) => {
      // 获取微应用配置
      let installAppMap = { ...viewStore.installAppMap }

      try {
        // 根据路径获取微应用config
        const appConfig = findMicroAppByPath(path)
        const routeObj = {
          appName: appConfig.name,
          path,
          fullPath,
          query,
          params,
          meta,
          name,
          id: appConfig.id
        }
        
        // 隐藏所有app页面 减少页面dom元素
        // const visibleAllApp = async () => {
        //   for (let appName in installAppMap) {
        //     if (appName === appConfig.name) {
        //       continue;
        //     }
        //     // 等待 parcel 挂载完成，然后再调用 update
        //     // await installAppMap[appName].mountPromise.then(()=>{
        //     //   if (installAppMap[appName].getStatus() === 'MOUNTED') {
        //     //     installAppMap[appName].update({
        //     //       routerEvent: {
        //     //         type: 'visible' // 如果不是当前活跃的就隐藏
        //     //       }
        //     //     })
        //     //   }
        //     // })
        //   }
        // }

        // 先判断微应用是否已加载过
        if (Object.hasOwnProperty.call(installAppMap, appConfig.name)) {
          const find = viewStore.visitedViews.find((item) => item.path === path)
          // 如果已经加载过页面了就切换tab

          if (find) {
            // 检测到路由的Tabs 是否已存在存在问题暂时注释
            // if (decodeURI(find.fullPath) !== decodeURI(fullPath) && find.path === path) {
            // visibleAllApp()
            // viewStore.delView(find)
            // setTimeout(() => {
            //   viewStore.addView({
            //     ...routeObj
            //   })
            // }, 50)

            // router.push({
            //   path,
            //   query,
            //   params
            // })

            // }, 50)


            // } else {
            // viewStore.activeTab = find

            // }
            // resolve(false)
            // return
            // } else {
            viewStore.activeTab = find
            // return
            // }
          } else {
            viewStore.addView({ ...routeObj })
          }

          // visibleAllApp()

          // installAppMap[appConfig.name] && installAppMap[appConfig.name].update({
          //   routerEvent: {
          //     ...routeObj,
          //     type: find ? 'replace' : 'push'
          //   }
          // })

          // 等待 parcel 挂载完成，然后再调用 update
          installAppMap[appConfig.name].mountPromise.then(()=>{
            installAppMap[appConfig.name].update({
              routerEvent: {
                ...routeObj,
                type: find ? 'replace' : 'push'
              }
            })
          })

          resolve(true)
          return
        }

        // 否则就首次加载微应用并跳转
        // visibleAllApp()
        clearTimeout(time)
        time = setTimeout(() => {
          installAppMap[appConfig.name] = loadMicroApp({
            ...appConfig,
            props: {
              $parentRouter: router,
              actions: actions,
              routerEvent: {
                ...routeObj,
                type: 'push'
              }
            },
            sandbox:{ speedy: true, experimentalStyleIsolation:true }
          })
          routeObj.title = sidebarRouters[path] || query.pageTabTitle
          viewStore.addView(routeObj)
          viewStore.pushInstallAppMap(installAppMap)
        }, 10);


        // setTimeout(() => {
        //   routeObj.title = sidebarRouters[path] || query.pageTabTitle
        //   viewStore.addView(routeObj)
        //   viewStore.pushInstallAppMap(installAppMap)
        // }, 500);

        resolve(true)
      } catch (err) {
        appStore.qiankunLoading = false
        reject(false)
      }
    })
  }

  // 打开tab
  openTab(routes) {
    let {
      path, // 普通路径
      fullPath, // 带参路径
      query, // query参数
      params,
      meta, // 其他参数
      name,
      next
    } = routes

    if (viewStore.activeTab.path === path) {
      return
    }

    if (!isMicroApp(path)) {
      // 如果是非微应用页面直接跳转
      this.createIframePage(path, fullPath, query, params, meta, name).then((bool) => {
        next(bool)
      })
    } else {
      // 否则就是微应用
      this.createMicoPage(path, fullPath, query, params, meta, name).then((bool) => {
        next(bool)
      })
    }

  }

  // 切换tab
  switchTab(item) {
    // if (item.path === store.getters['tabs/activeTab'].path) {
    //   return
    // }
    // router.push(item.fullPath)
  }

  closeTab(item) {
    // store.dispatch('tabs/closeTabsList', item)
  }
}

export default new Tabs()